package io.github.zhonglunsheng.controller;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import io.github.zhonglunsheng.common.ResponseData;
import io.github.zhonglunsheng.core.template.TemplateService;
import io.github.zhonglunsheng.domain.GenTable;
import io.github.zhonglunsheng.domain.SysGlobal;
import io.github.zhonglunsheng.domain.SysTpl;
import io.github.zhonglunsheng.domain.dto.CodeGenDTO;
import io.github.zhonglunsheng.domain.vo.TplCodeGenInfoVo;
import io.github.zhonglunsheng.service.CodeGenService;
import io.github.zhonglunsheng.service.SysGlobalService;
import io.github.zhonglunsheng.domain.bo.ImportTplBo;
import io.github.zhonglunsheng.service.SysTplService;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/codegen/tpl")
public class TplController {

    @Autowired
    private SysTplService sysTplService;

    @Autowired
    private SysGlobalService sysGlobalService;

    @Autowired
    private TemplateService templateService;

    @Autowired
    private CodeGenService codeGenService;

    @PostMapping("/list")
    public ResponseData list(@RequestBody SysTpl sysTpl) {
        return ResponseData.createSuccessResponse(sysTplService.query(sysTpl));
    }


    @GetMapping("/group/list")
    public ResponseData queryGroupName() {
        List<SysTpl> queryList = sysTplService.groupByTplGroupName();
        return ResponseData.createSuccessResponse(queryList.stream().map(SysTpl::getGroupName));
    }


    @PostMapping("/update")
    public ResponseData saveOrUpdateTpl(@RequestBody SysTpl sysTpl) {
        sysTpl.setUpdateTime(new Date());
        return ResponseData.createSuccessResponse(sysTplService.saveOrUpdate(sysTpl));
    }


    @GetMapping("/remove")
    public ResponseData remove(String id) {
        return ResponseData.createSuccessResponse(sysTplService.removeById(id));
    }


    @GetMapping("/group/tpl/info")
    public ResponseData tplGenInfo (String tplGroupName, String tableName) {
        List<SysTpl> sysTplList = sysTplService.queryByGroupName(tplGroupName);
        List<SysTpl> collect = sysTplList.stream().filter(item -> "1".equals(item.getStatus())).collect(Collectors.toList());
        // 获取全局变量
        CodeGenDTO codeGenDTO = new CodeGenDTO();
        codeGenDTO.setTableName(tableName);
        codeGenDTO.setData(new HashMap<>());
        Map<String, Object> genVariables = codeGenService.getAllVariable(codeGenDTO);


        List<TplCodeGenInfoVo> result = Lists.newArrayList();
        for (SysTpl tpl : collect) {
            result.add(TplCodeGenInfoVo.builder()
                    .id(tpl.getId())
                    .tplName(tpl.getTplName())
                    .tplFileName(templateService.generateTemplate(tpl.getFileName(), genVariables))
                    .tplCodeGenPath(templateService.generateTemplate(tpl.getFilePath(), genVariables))
                    .tplPath(tpl.getFilePath())
                    .status("1".equals(tpl.getStatus()) ? true : false)
                    .build());
        }
        return ResponseData.createSuccessResponse(result);
    }

    @PostMapping("/import")
    public ResponseData importTpl(MultipartFile file) throws IOException {
        String oriName = file.getOriginalFilename();
        // 下载到temp目录
        String basePath = "META-INF/resources/temp/projectCode/";
        Files.copy(file.getInputStream(), Paths.get(basePath), StandardCopyOption.REPLACE_EXISTING);
        return ResponseData.createSuccessResponse(sysTplService.importTpl(basePath + file.getOriginalFilename(),
                basePath + file.getName(), ImportTplBo.builder()
                        .basePrefix("#(projectCode." + file.getName() + ".basePath)")
                        .projectName(file.getName())
                        .build()));
    }
}
